#include <scwrapper.h>
#include <foolibc.h>

const int myport = 0;


/* KBDUS means US Keyboard Layout. This is a scancode table
*  used to layout a standard US keyboard. I have left some
*  comments in to give you an idea of what key is what, even
*  though I set it's array index to 0. You can change that to
*  whatever you want using a macro, if you wish! */
const unsigned char kbdus[128] =
{
    0,  27, '1', '2', '3', '4', '5', '6', '7', '8',	/* 9 */
  '9', '0', '-', '=', '\b',	/* Backspace */
  '\t',			/* Tab */
  'q', 'w', 'e', 'r',	/* 19 */
  't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n',	/* Enter key */
    0,			/* 29   - Control */
  'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';',	/* 39 */
 '\'', '`',   0,		/* Left shift */
 '\\', 'z', 'x', 'c', 'v', 'b', 'n',			/* 49 */
  'm', ',', '.', '/',   0,				/* Right shift */
  '*',
    0,	/* Alt */
  ' ',	/* Space bar */
    0,	/* Caps lock */
    0,	/* 59 - F1 key ... > */
    0,   0,   0,   0,   0,   0,   0,   0,
    0,	/* < ... F10 */
    0,	/* 69 - Num lock*/
    0,	/* Scroll Lock */
    0,	/* Home key */
    0,	/* Up Arrow */
    0,	/* Page Up */
  '-',
    0,	/* Left Arrow */
    0,
    0,	/* Right Arrow */
  '+',
    0,	/* 79 - End key*/
    0,	/* Down Arrow */
    0,	/* Page Down */
    0,	/* Insert Key */
    0,	/* Delete Key */
    0,   0,   0,
    0,	/* F11 Key */
    0,	/* F12 Key */
    0,	/* All other keys are undefined */
};

char getch() {
	while (1) {
		long code = getscancode();	// this is a blocking system call!
		if (!(code & 0x80)) {		// ignore when the key is released
			return kbdus[code];
		}
	}
}

void stdout(char *string, int port_dest) 
{
	struct message m;
	m.data = string;
	m.size = my_strlen(string)+1;
	m.dest_port = port_dest;
	m.src_port = myport;

	long status;
	do {
		status = send_msg(&m);
	} while (status != ALL_OK);	// send until we get succes, but only send once
}

void printchar(char ch) {
	char buf[2] = {0};
	buf[0] = ch;
	prints(buf);
}
void readline(char *dest, int size) 
{
	int count = 0;
	int ch = 0;

	char *d = dest;
	while (count++ < size && ch != '\n') {
		ch = *(d++) = getch();
		printchar(ch);
	}
	*(d++) = 0;
}

int main(int argc, char* argv[])
{
	const int status = create_mailbox(0, myport);
	if (status != ALL_OK) {
		while (1) {prints("Could not create mailbox0\n\0");}
	}
	
	createprocess(1);
	createprocess(2);

	while (1) {
		char buf[200] = {0};
		readline(buf, 200);
		stdout(buf, 1);
	}

	while (1) {pause(100);}
}

